//#include "StdAfx.h"
#include "base_mem_alloc.h"

CBaseBlockMem::CBaseBlockMem(int block_num, int block_size )
{
	m_block_num  = block_num;
	m_block_size = block_size;
	m_pInitBuf  = new char[m_block_num*m_block_size];
	assert( m_pInitBuf != NULL );
	m_pMemAllocFlag = new PMemAllocFlag[m_block_num];
	for( int i = 0; i < m_block_num; i++ )
	{
		m_pMemAllocFlag[i] = new SMemAllocFlag;
		char * p = m_pInitBuf + i*m_block_size;
		m_pMemAllocFlag[i]->init( p, m_block_size );
	}
}
CBaseBlockMem::~CBaseBlockMem(void)
{
	for( int i = 0; i < m_block_num; i++ )
	{
		delete m_pMemAllocFlag[i];
	}
	delete []m_pMemAllocFlag;

	if( m_pInitBuf != NULL )
		delete []m_pInitBuf;
}
void * CBaseBlockMem::Alloc( int size )
{
	if( size > m_block_size )
		return NULL;
	
	void * p = NULL;
	m_optex.Enter();
	for( int i = 0; i < m_block_num; i++ )
	{
		if( !m_pMemAllocFlag[i]->m_flag )
		{
			p = m_pMemAllocFlag[i]->alloc();
			break;
		}
	}
	m_optex.Leave();

	if( p == NULL )
		p = new char[size];
	return p;
}
void CBaseBlockMem::Free( void * p )
{
	bool bFree = false;
	m_optex.Enter();
	for( int i = 0; i < m_block_num; i++ )
	{
		if( m_pMemAllocFlag[i]->m_p == p )
		{
			m_pMemAllocFlag[i]->free();
			bFree = true;
			break;
		}
	}
	m_optex.Leave();
	if( !bFree )
		delete [](char*)p;
}

